package com.coder.gmall.gateway.filter;

import com.coderg.gmall.common.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description 效验是否携带token，以及ip是否合法
 * @Author CoderG
 * @Date 2025/6/1 17:02
 **/
@Component
@Order(-1)
public class TokenFilter implements GlobalFilter {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //两种方式 获取用户携带token 和redis里面 保存的token比较
        //直接通过ip获取redis token

        //查看参数里面是否携带token
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String token = queryParams.getFirst("token");
        //没有token 查看heard里面是否携带
        if (StringUtils.isEmpty(token)) {
            token = request.getHeaders().getFirst("token");
            //没有token 查看cookie里面是否携带
            if (StringUtils.isEmpty(token)) {
                HttpCookie httpCookie = request.getCookies().getFirst("token");
                if (httpCookie != null) {
                    token = httpCookie.getValue();
                }
            }
        }
        // 全部没有则跳转登录页面
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }
        String gatwayIpAddress = IpUtil.getGatwayIpAddress(request);
        String redisToken = stringRedisTemplate.opsForValue().get(gatwayIpAddress);
        //放行
        if (token.equals(redisToken)) {
            //放固定的heard oauth
            request.mutate().header("Authorization", "Bearer " + redisToken);

            return chain.filter(exchange);
        } else {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

    }
}
